#!/bin/bash
g_printout="__printout__"
g_call="__call__"
g_log="__log__"
g_values="__values__"
g_progress="__progress__"
g_split_flag="____BINGO_FILTER____"


function _report() {
    [ -n "$1" ] && p=$(echo "$1" | tr '\n' ' ' | awk '$1=$1')
    [ -n "$2" ] && s=$(echo "$2" | tr '\n' ' ' | awk '$1=$1')
    [ -n "$3" ] && i=$(echo "$3" | tr '\n' ' ' | awk '$1=$1')
    [ -n "$4" ] && d=$(echo "$4" | tr '\n' ' ' | awk '$1=$1')
    cat <<EOF >${g_task_dir}/${g_progress}
{
    "progress": "$p",
    "status": "$s",
    "info": "$i",
    "download": "$d"
}
EOF
    chmod 777 ${g_task_dir}/__*
}

# 进度和提示栏内容设置接口 #
# $1: progress
# $2: information
# $3: file for download
function ReportInfo() {
    _report "$1" "RUNNING" "$2" "$3"
}

# 进度和提示栏错误设置接口 #
# $1: progress
# $2: information
# $3: file for download
function ReportErr() {
    _report "$1" "FAILED" "$2" "$3"
    exit 1
}

# 输出栏打印接口 #
# $1: information
function PrintOut() {
    echo "$(date +'%F %T'): $1" >> ${g_task_dir}/${g_printout}
    chmod 777 ${g_task_dir}/${g_printout}
}

# 任务日志打印接口 #
# $1: information for log
function PrintLog() {
    echo "$(date +'%F %T') $1" >> "${g_task_dir}/${g_log}"
    chmod 777 "${g_task_dir}/${g_log}"
}

# 打印每步的执行结果, 成功或者失败
# $1: 执行结果, 0成功, 非0失败
# $2: information
# $3: progress
# $4: 是否打印到输出栏中 #
function PrintStep() {
    local ret=$1
    local info=$2
    local prog=$3
    local print=$4
    if [ $ret -eq 0 ]; then
        [ -n "${print}" ] && PrintOut "${info}    ......Success"
        ReportInfo "${prog}" "${info}    ......Success"
    else
        [ -n "${print}" ] && PrintOut "${info}    ......Failed"
        ReportErr "${prog}" "${info}    ......Failed"
    fi
}

# 统一压缩接口 #
# $1 压缩的目录
# $2 文件名,不带后缀
# echo 带后缀的文件绝对路径 #
function Compress() {
    local dst_path=$1
    local dst_file=$2
    cd ${dst_path} || return 1

    which tar &>/dev/null
    if [ $? -eq 0 ]; then
        tar zcf ${dst_file}.tar.gz * &>/dev/null
        [ -f ${dst_file}.tar.gz ] || return 1
        chmod 777 ${dst_file}.tar.gz &>/dev/null
        echo "${dst_path}/${dst_file}.tar.gz"
        return 0
    fi

    which zip &>/dev/null
    if [ $? -eq 0 ]; then
        zip ${dst_file}.zip * &>/dev/null
        [ -f ${dst_file}.zip ] || return 1
        chmod 777 ${dst_file}.zip &>/dev/null
        echo "${dst_path}/${dst_file}.zip"
        return 0
    fi
    return 1
}
